package com.kcsj.filter;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.kcsj.util.JWTResult;
import com.kcsj.util.MessageHelper;
import com.kcsj.util.TokenHelper;
import lombok.SneakyThrows;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "Filter", urlPatterns = { "/*"})
public class MyFilter implements javax.servlet.Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {

    }

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //类型转换
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //请求的URL
        String path=request.getRequestURI().toLowerCase();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        if(path.contains("/login")||path.contains("/register.ctl")||path.contains("/active.ctl")||path.contains("/rfid.ctl")){
            chain.doFilter(request,response);
        }else {
            try{
                //通过header获取token
                String token = request.getHeader("token");
                //验证token，返回jwtResult,存放token解码出来的结果
                JWTResult jwtResult = TokenHelper.verify(token);
                //设置request的节点
                this.setRequestAttribute(jwtResult,request);
                //放行
                chain.doFilter(request,response);
            }catch (TokenExpiredException e) {
                try {
                    String flushToken = request.getHeader("flushToken");
                    JWTResult jwtResult = TokenHelper.verify(flushToken);
                    this.setRequestAttribute(jwtResult,request);
                    if(!path.contains("/notice")||!request.getMethod().equals("GET")){
                        String newToken = TokenHelper.getToken(jwtResult);
                        String newFlushToken = TokenHelper.getFlushToken(jwtResult);
                        response.addHeader("token",newToken);
                        response.addHeader("flushToken",newFlushToken);
                    }
                    chain.doFilter(request,response);
                } catch (TokenExpiredException error) {
                    error.printStackTrace();
                    JSONObject message = MessageHelper.tokenInvalidation();
                    response.getWriter().println(message);
                }
            } catch (Exception e){

                JSONObject message = MessageHelper.error();
                response.getWriter().println(message);
                e.printStackTrace();
            }
        }
    }
    /**
     * 将token解码出来的结果，set到request的节点中
     * request.setAttribute();该方法只在本次请其中生效
     */
    private void setRequestAttribute(JWTResult jwtResult,HttpServletRequest request){
        Integer userId = jwtResult.getUserId();
        String username = jwtResult.getUsername();
        String roleName = jwtResult.getRoleName();
        request.setAttribute("userId",userId);
        request.setAttribute("username",username);
        request.setAttribute("roleName",roleName);
    }
}

